package com.zh.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

// 使用拦截器实现token 转发
@Slf4j
public class TokenInterceptor implements RequestInterceptor {
    // 读取yam 中的 配置
    @Value("${sa-token.token-name}")
    private  String tokenName;


    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 1.拿到请求头中的Token - 请求
        // RequestContextHolder : 请求上下文对象,用来获取请求,需要转成子类
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 2 、拿到satoken
        String satoken = requestAttributes.getRequest().getHeader(tokenName);
        //通过requestTemplate可以对feign的请求头进行设置
        requestTemplate.header(tokenName,satoken);
        log.info("Feign拦截器转发Token{}," , satoken);
    }
}
